/*
 * @ProjectName: 编程学习
 * @Copyright:   2021 HangZhou Yiyuery Dev, Ltd. All Right Reserved.
 * @address:     微信搜索公众号「架构探险之道」获取更多资源。
 * @date:        2021/1/2 4:58 下午
 * @blog:         https://yiyuery.blog.csdn.net/
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package pub.dsb.example.thread;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 *  https://leetcode-cn.com/problems/the-dining-philosophers/
 * </p>
 *
 * @author Yiyuery
 * @date 2021/1/2 4:58 下午
 * @sine 0.0.1
 */
public class LC1226Test {

}
class DiningPhilosophers {
    private ArrayList<ReentrantLock> locks = new ArrayList<>();
    public DiningPhilosophers() {
        for(int i=0; i<5; i++) {
            locks.add(new ReentrantLock());
        }
    }

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
        Lock left = locks.get((philosopher + 4) % 5);
        Lock right = locks.get(philosopher);

        left.lock();
        right.lock();

        pickLeftFork.run();
        pickRightFork.run();
        eat.run();
        putLeftFork.run();
        putRightFork.run();

        left.unlock();
        right.unlock();
    }
}
